import React, { Component } from 'react';
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  ScrollView,
  StyleSheet,
  Animated,
  Platform,
} from 'react-native';
import Video from 'react-native-video';
import FontFamilys from '../../../utils/FontFamilys';

import NavCon from '../../Public/NavCon';
import PxToDp from '../../../utils/PxToDp';

/* global host */
let timer;
class VoiceList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pause: true,       // 播放/暂停
      progress: new Animated.Value(0),
      play: false,
    };
  }

  _voicePaused() {
    this.setState({
      play: true,
      pause: !this.state.pause,
    });

    console.log('voicePaused');

    if (this.state.pause) {
      timer = setInterval(() => {
        this._animation();
      }, 1000);
    } else if (timer) {
      clearInterval(timer);
    }
  }

  _animation() {
    this.state.progress.setValue(0);
    Animated.timing(this.state.progress, {
      toValue: 1,
      duration: 1000,
    }).start();
  }

  componentWillMount() {
    timer = setInterval(() => {
      this._animation();
    }, 1000);
  }

  render() {
    const { carName, voiceUrl, duration, time } = this.props;

    // const length = userName.length;
    // const shortName = userName.substring(length - 2, length);
    const showTime = `${time.substring(0, 10)} ${time.substring(11, 16)}`;
    const voiceFile = `${host}/static/${voiceUrl}`;
    const showDuration = `${duration}"`;
    const bgColor = this.state.play ? 'transparent' : '#f65252';
    const vWidth = duration > 5 ? duration * 5 : 30;

    return (
      <View style={[styles.voiceList]}>
        <View style={[styles.timeRow]}>
          <View style={styles.timerWrapper}>
            <Text style={[styles.time]}>{showTime}</Text>
          </View>
        </View>

        <View style={[styles.voiceContainer]}>

          <TouchableOpacity
            activeOpacity={1}
            style={[styles.voiceWrapper, { width: vWidth }]}
            onPress={() => this._voicePaused()}
          />
          <View style={{ marginLeft: PxToDp(5) }}>
            <View style={[styles.redDot, { backgroundColor: bgColor }]} />
            <Text style={styles.duration}>{showDuration}</Text>
          </View>
          <Image style={[styles.triangle]} source={require('../../../img/home/triangle3.png')} />
          {
            !this.state.pause ?
              <Image
                style={{ position: 'absolute',
                  left: Platform.OS === 'ios' ? PxToDp(20) : PxToDp(20),
                  top: Platform.OS === 'ios' ? PxToDp(11) : PxToDp(11),
                  width: 11,
                  height: 15,
                  zIndex: 15,
                }}
                source={require('../../../img/home/voice1.gif')}
              /> :
              <Image
                style={{ position: 'absolute',
                  left: Platform.OS === 'ios' ? PxToDp(20) : PxToDp(20),
                  top: Platform.OS === 'ios' ? PxToDp(11) : PxToDp(11),
                  width: 11,
                  height: 15,
                  zIndex: 15,
                }}
                source={require('../../../img/home/soundIcon.png')}
              />
          }
          {
            voiceFile ?
              <Video
                source={{ uri: voiceFile }}
                volume={1.0}
                paused={this.state.pause}
                playInBackground
              /> : null
          }
        </View>
        <View style={[styles.storeWrapper]}>
          <Text style={[styles.store]}>{carName}</Text>
        </View>
      </View>
    );
  }
}

class LeavingMessage extends Component {
  constructor(props) {
    super(props);
    const { moreVoices } = this.props;
    const ps = [];
    if (moreVoices && moreVoices.length > 0) {
      for (let k = 0; k < moreVoices.length; k += 1) {
        ps.push(new Animated.Value(0));
      }
    }

    this.state = {
      voiceFile: null, // 音频文件
      pause: true,       // 播放/暂停
      ps,
    };
  }

  _goBack() {
    this.props.navigator.pop();
  }

  render() {
    const { moreVoices, user } = this.props;
    const msgs = moreVoices || null;
    const title = `${user.username}的留言`;
    return (
      <View style={[styles.flex, styles.bgColor, styles.titleTop]}>
        <NavCon currentTitle={title} bgColor="#fff" onPress={() => this._goBack()} />
        <ScrollView>
          {
            msgs ? msgs.map((msg, index) => (
              msg.seconds ?
                <VoiceList
                  key={msg.created_at}
                  carName={user.lookcar}
                  userName={user.username}
                  duration={msg.seconds}
                  voiceUrl={msg.file}
                  time={msg.created_at}
                  index={index}
                  progress={this.state.ps[index]}
                /> : null
            )) : null
          }
        </ScrollView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  flex: {
    flex: 1,
  },
  bgColor: {
    backgroundColor: '#f7f8fa',

  },
  voiceList: {
    width: '100%',
    paddingTop: PxToDp(40),
    paddingLeft: PxToDp(20),
  },
  timeRow: {
    alignItems: 'center',
  },
  timerWrapper: {
    justifyContent: 'center',
    alignItems: 'center',
    height: PxToDp(24),
    paddingLeft: PxToDp(12),
    paddingRight: PxToDp(12),
    backgroundColor: '#efefef',
    borderRadius: PxToDp(100),
  },
  time: {
    color: '#8b8c8e',
    fontSize: PxToDp(12),
    fontFamily: FontFamilys(),
  },
  storeWrapper: {
    width: '100%',
    marginTop: PxToDp(2),
  },
  store: {
    color: '#8b8c8e',
    fontSize: PxToDp(12),
    fontFamily: FontFamilys(),
  },
  voiceContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: PxToDp(27),
    paddingLeft: PxToDp(10),
  },
  voiceWrapper: {
    justifyContent: 'center',
    alignItems: 'flex-end',
    height: PxToDp(38),
    paddingRight: PxToDp(30),
    backgroundColor: '#418cff',
    borderRadius: PxToDp(2),
    marginLeft: PxToDp(-3),
    zIndex: 5,
    maxWidth: PxToDp(300),
  },
  triangle: {
    position: 'absolute',
    zIndex: 0,
  },
  duration: {
    marginTop: PxToDp(3),
    color: '#121212',
    fontSize: PxToDp(13),
  },
  redDot: {
    marginLeft: PxToDp(2),
    width: PxToDp(7),
    height: PxToDp(7),
    backgroundColor: '#f65252',
    borderRadius: PxToDp(4),
  },
  titleTop: {
    marginTop: Platform.OS === 'ios' ? 20 : 0,
  },
});
export default LeavingMessage;
